﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module;

namespace HeThongSpa.QuanTriHeThong.DanhMuc
{
    public partial class DanhMucDichVu : Page
    {
        private const int PageSize = 20;
        private readonly SelectAll _selectAll = new SelectAll();

        private Module.QuanTriHeThong.DanhMuc.DanhMucDichVu _danhMucDichVu =
            new Module.QuanTriHeThong.DanhMuc.DanhMucDichVu();

        private int _totalrow;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                SelectAllThue();
                SelectAllNhomDichVu();
                LoadPage();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["CheckRefresh"] = Session["CheckRefresh"];
        }

        private void SelectAllThue()
        {
            ddlThue.DataSource = _selectAll.SelectAllThue();
            ddlThue.DataTextField = "Thue";
            ddlThue.DataValueField = "ID";
            ddlThue.DataBind();
            ddlThue.Items.Insert(0, new ListItem("Chọn", ""));
        }

        private void SelectAllNhomDichVu()
        {
            ddlNhomDichVu.DataSource = _selectAll.SelectAllNhomDichVu();
            ddlNhomDichVu.DataTextField = "TenNhomDichVu";
            ddlNhomDichVu.DataValueField = "MaNhomDichVu";
            ddlNhomDichVu.DataBind();
            ddlNhomDichVu.Items.Insert(0, new ListItem("Chọn", ""));
        }

        private void LoadPage()
        {
            _danhMucDichVu = new Module.QuanTriHeThong.DanhMuc.DanhMucDichVu();
            if (hfTimKiem.Value.Equals("true"))
            {
                _danhMucDichVu.MaDichVu = txtMaDichVu.Text.Trim();
                _danhMucDichVu.TenDichVu = txtTenDichVu.Text.Trim();
                _danhMucDichVu.MaNhomDichVu = ddlNhomDichVu.SelectedValue.Trim();
            }
            gvDanhMuc.DataSource = _danhMucDichVu.SelectAll(_danhMucDichVu, Convert.ToInt32(hfPageIndex.Value.Trim()),
                PageSize, out _totalrow);
            gvDanhMuc.DataBind();
            GeneratePager(_totalrow, PageSize, Convert.ToInt32(hfPageIndex.Value.Trim()));
            Session["CheckRefresh"] = Server.UrlEncode(DateTime.Now.ToString(CultureInfo.InvariantCulture));
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    _danhMucDichVu.MaDichVu = txtMaDichVu.Text.Trim();
                    _danhMucDichVu.TenDichVu = txtTenDichVu.Text.Trim();
                    _danhMucDichVu.MaNhomDichVu = ddlNhomDichVu.SelectedValue.Trim();
                    _danhMucDichVu.GiaDichVu = Convert.ToDouble(txtGiaDichVu.Text.Trim());
                    _danhMucDichVu.SoLanThucHien = Convert.ToInt32(txtSoLanThucHien.Text.Trim());
                    _danhMucDichVu.ThoiGianThucHien = Convert.ToDouble(txtThoiGianThucHien.Text.Trim());
                    _danhMucDichVu.Thue = ddlThue.SelectedValue.Trim();
                    _danhMucDichVu.TaiKhoan = Session["username"].ToString().Trim();
                    if (txtMaDichVu.Enabled) // Kiểm tra nếu mã có trạng thái enabled = true thì là thêm mới
                    {
                        var CheckMa = _danhMucDichVu.SelectById(_danhMucDichVu.MaDichVu).Rows.Count > 0;
                        if (!CheckMa)
                        {
                            if (!_danhMucDichVu.Insert(_danhMucDichVu))
                                ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                                    "bootbox.alert('Cập nhật thất bại, vui lòng thử lại.')", true);
                        }
                        else
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                                "bootbox.alert('Mã chức vụ đã tồn tại, vui lòng nhập mã khác.')", true);
                    }
                    else // Nếu không thì sẽ là update
                    {
                        if (!_danhMucDichVu.Insert(_danhMucDichVu))
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                                "bootbox.alert('Cập nhật thất bại, vui lòng thử lại.')", true);
                    }
                }
                ResetPage();
            }
        }

        protected void btnXoa_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    foreach (GridViewRow gvrow in gvDanhMuc.Rows)
                    {
                        var checkId = (CheckBox)gvrow.FindControl("check_id");
                        if (!checkId.Checked) continue;
                        var dataKey = gvDanhMuc.DataKeys[gvrow.RowIndex];
                        if (dataKey == null) continue;
                        if (dataKey.Values == null) continue;
                        var id = dataKey.Values["MaDichVu"].ToString();
                        _danhMucDichVu.Delete(id, Session["username"].ToString().Trim());
                    }
                }
                ResetPage();
            }
        }

        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            txtMaDichVu.Enabled = true;
            hfTimKiem.Value = "true";
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void btnNhapLai_Click(object sender, EventArgs e)
        {
            ResetPage();
        }

        protected void gvDanhMuc_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow ||
                (e.Row.RowState != DataControlRowState.Normal && e.Row.RowState != DataControlRowState.Alternate))
                return;
            var checkId = (CheckBox)e.Row.Cells[0].FindControl("check_id");
            var checkallId = (CheckBox)gvDanhMuc.HeaderRow.FindControl("checkall_id");
            checkId.Attributes["onclick"] = string.Format
                (
                    "javascript:checkClick(this,'{0}');",
                    checkallId.ClientID
                );
        }

        protected void btnSua_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                    ResetPage();
                else
                {
                    txtMaDichVu.Text = ((LinkButton)sender).CommandArgument;
                    txtMaDichVu.Enabled = false;
                    var dt = _danhMucDichVu.SelectById(txtMaDichVu.Text.Trim());
                    if (dt.Rows.Count <= 0) return;
                    txtTenDichVu.Text = dt.Rows[0]["TenDichVu"].ToString().Trim();
                    txtTenDichVu.Focus();
                    ddlNhomDichVu.SelectedValue = dt.Rows[0]["MaNhomDichVu"].ToString().Trim();
                    txtGiaDichVu.Text = dt.Rows[0]["GiaDichVu"].ToString().Trim();
                    txtSoLanThucHien.Text = dt.Rows[0]["SoLanThucHien"].ToString().Trim();
                    txtThoiGianThucHien.Text = dt.Rows[0]["ThoiGianThucHien"].ToString().Trim();
                    ddlThue.SelectedValue = dt.Rows[0]["Thue"].ToString().Trim();
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    if (!_danhMucDichVu.Delete((((LinkButton)sender).CommandArgument).Trim(), Session["username"].ToString().Trim()))
                        ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                            "bootbox.alert('Xóa thất bại.')", true);
                }
                ResetPage();
            }
        }

        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "PageNo") return;
            hfPageIndex.Value = e.CommandArgument.ToString();
            LoadPage();
            e.Item.Attributes.Add("disabled", "disabled");
        }

        public void GeneratePager(int totalRowCount, int pageSize, int currentPage)
        {
            const int totalLinkInPage = 4;
            var totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            var startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            var lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            var pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
            {
                pageLinkContainer.Add(new ListItem("«", "1", currentPage != 1));
            }
            for (var i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture),
                    i.ToString(CultureInfo.InvariantCulture), currentPage != i));
            }
            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("»", totalPageCount.ToString(CultureInfo.InvariantCulture),
                    currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }

        private void ResetPage()
        {
            txtMaDichVu.Text = string.Empty;
            txtMaDichVu.Enabled = true;
            txtTenDichVu.Text = string.Empty;
            ddlNhomDichVu.SelectedValue = string.Empty;
            txtGiaDichVu.Text = string.Empty;
            txtSoLanThucHien.Text = string.Empty;
            txtThoiGianThucHien.Text = string.Empty;
            ddlThue.SelectedValue = string.Empty;
            hfTimKiem.Value = "false";
            hfPageIndex.Value = "1";
            LoadPage();
        }
    }
}